import os
import sys

libPaths = []
#from here (app folder) back to appsroot
currentPath = os.path.dirname(__file__)
basePath = os.path.normpath(os.path.join(currentPath, ".."))
third_party_libpath = os.path.join(basePath, "third_party_packages")

libPaths.append(os.path.join(third_party_libpath, "mako_lib.zip"))
libPaths.append(os.path.join(third_party_libpath, "webob_lib.zip"))
libPaths.append(os.path.join(third_party_libpath, "paste_lib.zip"))

#append third party libs to sys.path
for lib in libPaths:
    sys.path.insert(0, lib)

#add the currrent path
#sys.path.insert(0, currentPath)

import webapp2
from webapp2_extras import mako
#from webapp2_extras import jinja2

#where to find the templates
mako.default_config.update({"template_path" : os.path.join(os.path.dirname(__file__), "templates")})
jinja2.default_config.update({"template_path" : os.path.join(os.path.dirname(__file__), "templates")})

#import socket
#
#def ip():
#    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#    s.connect(('google.com', 0))
#    return s.getsockname()[0]


class HelloWebapp2(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello, webapp2!')

##using mako
#class BaseHandler(webapp2.RequestHandler):
#    @webapp2.cached_property
#    def mako(self):
#        # Return a Mako renderer cached in the app registry
#        return mako.get_mako(app=self.app)
#
#    def render_response(self, _template, **context):
#        # Renders a template and writes the result to the response.
#        rv = self.mako.render_template(_template, **context)
#        self.response.write(rv)


#using jinja2
class BaseHandler(webapp2.RequestHandler):
    @webapp2.cached_property
    def jinja2(self):
        # Return a Jinja2 renderer cached in the app registry
        return jinja2.get_jiaja2(app=self.app)

    def render_response(self, _template, **context):
        # Renders a template and writes the result to the response.
        rv = self.jinja2.render_template(_template, **context)
        self.response.write(rv)


class MyHandler(BaseHandler):
    def get(self):
        context = {"message": "Hello, world"}
        self.render_response("a.html", **context)


class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.write("""
          <html>
            <body>
              <form action="/shutdown" method="link">
                <div><input type="submit" value="Shutdown"></div>
              </form>
            </body>
          </html>""")


class shutdown(webapp2.RequestHandler):
    def get(self):
        self.response.write('<html><body>Shutting down...<pre>')
        self.response.write('</pre></body></html>')
        os.system("shutdown -p -f")
